package high.concurrent.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * sentinel流控生效时触发的异常对应的返回值配置
 */
@Component
public class SentinelExceptionConfig implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {

        Map<String, Object> info = new HashMap<String, Object>();

        if(e instanceof FlowException){
            info.put("code", -1);
            info.put("msg", "限流异常");
        }else if(e instanceof DegradeException){
            info.put("code", -2);
            info.put("msg", "降级异常");
        }else if(e instanceof ParamFlowException){
            info.put("code", -3);
            info.put("msg", "热点参数异常");
        }else if(e instanceof SystemBlockException){
            info.put("code", -4);
            info.put("msg", "系统负载异常");
        }else if(e instanceof AuthorityException){
            info.put("code", -5);
            info.put("msg", "授权异常");
        }
        // 浏览器要返回200
        httpServletResponse.setStatus(200);
        // 请求头使用的类型和字符编码
        httpServletResponse.setHeader("content-type", "application/json;charset=UTF-8");
        // 把异常发送出去
        httpServletResponse.getWriter().write(JSONObject.toJSONString(info));
    }
}
